<template>
  <div
    ref="forwardScrollBoxRef"
    class="forward-scroll-box"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <div ref="forwardContentRef">
      <slot name="forwardContent"></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue';

  // 定义组件属性
  interface Props {
    speed?: number;
  }

  const props = withDefaults(defineProps<Props>(), {
    speed: 1,
  });

  // 定义响应式引用
  const forwardScrollBoxRef = ref<HTMLElement | null>(null);
  const forwardContentRef = ref<HTMLElement | null>(null);

  // 定义变量
  let containerHeight = 0;
  let contentHeight = 0;
  let heightDifference = 0;
  let scrollTop = 0;
  let scrollInterval: number | null = null;

  // 方法定义
  function clearScrollInterval() {
    if (scrollInterval !== null) {
      clearInterval(scrollInterval);
      scrollInterval = null;
    }
  }

  function start() {
    clearScrollInterval();
    calculateHeights();
    startScrolling();
  }

  function calculateHeights() {
    if (forwardScrollBoxRef.value && forwardContentRef.value) {
      containerHeight = forwardScrollBoxRef.value.getBoundingClientRect().height;
      contentHeight = forwardContentRef.value.getBoundingClientRect().height;
      heightDifference = contentHeight - containerHeight;
    }
  }

  function startScrolling() {
    if (!forwardScrollBoxRef.value) return;

    scrollInterval = window.setInterval(() => {
      if (heightDifference >= scrollTop) {
        if (forwardScrollBoxRef.value) {
          scrollTop = forwardScrollBoxRef.value.scrollTop += props.speed;
        }
      } else {
        if (forwardScrollBoxRef.value) {
          scrollTop = forwardScrollBoxRef.value.scrollTop = 0;
          clearScrollInterval();
          startScrolling();
        }
      }
    }, 50);
  }

  function handleMouseEnter() {
    clearScrollInterval();
  }

  function handleMouseLeave() {
    startScrolling();
  }

  // 暴露方法给父组件
  defineExpose({
    start,
  });

  // 组件挂载时初始化
  onMounted(() => {
    // 可以在这里添加初始化逻辑
  });

  // 组件卸载时清理
  onUnmounted(() => {
    clearScrollInterval();
  });
</script>

<style scoped>
  .forward-scroll-box {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: hidden;
  }

  .forward-scroll-box::-webkit-scrollbar {
    display: none;
  }

  .forward-scroll-box::-webkit-scrollbar-track-piece {
    background: #0e1d28;
  }

  .forward-scroll-box::-webkit-scrollbar-thumb {
    background: #2d6358;
    border: none;
  }
</style>
